package pers.supeijin.devtools.converter.utils;


import com.intellij.lang.Language;
import com.intellij.lang.javascript.psi.JSExpressionStatement;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import pers.supeijin.devtools.converter.entity.OnFilterListener;
import pers.supeijin.devtools.converter.entity.OnHandleXmlAttributeListener;

public class CommonUtils {
	public static PsiFile copyFile(Project project, PsiFile psiFile) {
		Language language = PsiUtilCore.getDialect(psiFile);
		PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);
		return psiFileFactory.createFileFromText(psiFile.getName(), language, psiFile.getText());
	}

	public static void handleXmlAttributes(XmlTag xmlTag, OnHandleXmlAttributeListener listener) {
		if (xmlTag != null && listener != null) {
			XmlAttribute[] attributes = xmlTag.getAttributes();
			handleXmlAttributes(attributes,listener);
		}
	}

	public static void handleXmlAttributes(XmlAttribute[] attributes, OnHandleXmlAttributeListener listener) {
		if (attributes != null && attributes.length>0 && listener != null) {
			for (XmlAttribute it : attributes) {
				listener.handleAttribute(it);
			}
		}
	}

	public static List<XmlAttribute> getFilterAttributeList(XmlTag xmlTag, OnFilterListener<XmlAttribute> listener) {
		if (listener != null && xmlTag != null) {
			XmlAttribute[] attributes = xmlTag.getAttributes();
			return Arrays.stream(attributes)
					.filter(attribute -> listener.filter(attribute))
					.collect(Collectors.toList());
		}
		return new ArrayList<>();
	}

	public static JSExpressionStatement[] getJSExpressionStatements(PsiElement psiElement,OnFilterListener<JSExpressionStatement> filterListener){
		PsiElement[] psiElements = PsiTreeUtil.collectElements(psiElement, element -> {
			if (element instanceof JSExpressionStatement) {
				if (filterListener != null) {
					return filterListener.filter((JSExpressionStatement) element);
				}
				return true;
			}
			return false;
		});
		int length = psiElements.length;
		JSExpressionStatement[] statements = new JSExpressionStatement[length];
		for (int i = 0; i < length; i++) {
			statements[i]= (JSExpressionStatement) psiElements[i];
		}
		return statements;
	}
}
